<template>
  <div class="max-w-4xl mx-auto p-4">
    <!-- 搜索和添加区域 -->
    <div class="mb-6 flex gap-4">
      <input v-model="searchQuery" type="text" placeholder="搜索待办事项..."
        class="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent" />
      <button @click="showAddModal = true"
        class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors">
        添加待办
      </button>
    </div>

    <!-- 状态过滤 -->
    <div class="mb-4 flex gap-2">
      <button v-for="status in ['all', 'todo', 'in-progress', 'completed']" :key="status"
        @click="currentFilter = status" :class="[
          'px-3 py-1 rounded-full text-sm transition-colors',
          currentFilter === status
            ? 'bg-blue-500 text-white'
            : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
        ]">
        {{ statusLabels[status] }}
      </button>
    </div>

    <!-- 待办列表 -->
    <div class="space-y-4">
      <div v-for="todo in filteredTodos" :key="todo.id"
        class="bg-white p-4 rounded-lg shadow hover:shadow-md transition-shadow">
        <div class="flex items-start justify-between">
          <div class="flex-1">
            <h3 class="text-lg font-medium">{{ todo.title }}</h3>
            <div class="mt-2 prose prose-sm max-w-none" v-html="renderMarkdown(todo.description)"></div>
            <div class="mt-2 flex gap-2">
              <span :class="[
                'px-2 py-1 rounded-full text-xs',
                statusClasses[todo.status]
              ]">
                {{ statusLabels[todo.status] }}
              </span>
              <span class="text-gray-500 text-sm py-1">
                创建于: {{ formatDate(todo.createdAt) }}
              </span>
              <div class="ml-auto flex items-center">
                <span v-for="star in 5" :key="star" class="text-lg"
                  :class="star <= todo.rating ? 'text-yellow-400' : 'text-gray-300'">
                  ★
                </span>
              </div>
            </div>
          </div>
          <div class="flex gap-2">
            <button @click="editTodo(todo)" class="p-2 text-gray-600 hover:text-blue-500 transition-colors">
              编辑
            </button>
            <button @click="deleteTodo(todo.id)" class="p-2 text-gray-600 hover:text-red-500 transition-colors">
              删除
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑模态框 -->
    <div v-if="showAddModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg p-6 w-full max-w-2xl mx-4">
        <h2 class="text-xl font-bold mb-4">{{ editingTodo ? '编辑待办' : '添加待办' }}</h2>
        <form @submit.prevent="saveTodo">
          <div class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700">标题</label>
              <input v-model="todoForm.title" type="text"
                class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                required />
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700">描述 (支持 Markdown)</label>
              <textarea v-model="todoForm.description" rows="4"
                class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"></textarea>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700">状态</label>
              <select v-model="todoForm.status"
                class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                <option value="todo">待办</option>
                <option value="in-progress">执行中</option>
                <option value="completed">已完成</option>
              </select>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700">星级</label>
              <div class="flex gap-1 mt-1">
                <button v-for="star in 5" :key="star" type="button" @click="todoForm.rating = star"
                  class="text-2xl focus:outline-none"
                  :class="star <= todoForm.rating ? 'text-yellow-400' : 'text-gray-300'">
                  ★
                </button>
              </div>
            </div>
          </div>
          <div class="mt-6 flex justify-end gap-3">
            <button type="button" @click="showAddModal = false"
              class="px-4 py-2 text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 transition-colors">
              取消
            </button>
            <button type="submit"
              class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors">
              保存
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { marked } from 'marked'
import { format } from 'date-fns'
import { useLocalStorage } from '@vueuse/core'

const todos = useLocalStorage('todos', [])
const searchQuery = ref('')
const currentFilter = ref('all')
const showAddModal = ref(false)
const editingTodo = ref(null)

const todoForm = ref({
  title: '',
  description: '',
  status: 'todo',
  rating: 0
})

const statusLabels = {
  'all': '全部',
  'todo': '待办',
  'in-progress': '执行中',
  'completed': '已完成'
}

const statusClasses = {
  'todo': 'bg-yellow-100 text-yellow-800',
  'in-progress': 'bg-blue-100 text-blue-800',
  'completed': 'bg-green-100 text-green-800'
}

const filteredTodos = computed(() => {
  return todos.value
    .filter(todo => {
      if (currentFilter.value === 'all') return true
      return todo.status === currentFilter.value
    })
    .filter(todo => {
      if (!searchQuery.value) return true
      return todo.title.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
        todo.description.toLowerCase().includes(searchQuery.value.toLowerCase())
    })
})

const renderMarkdown = (text) => {
  return marked(text || '')
}

const formatDate = (date) => {
  return format(new Date(date), 'yyyy-MM-dd HH:mm')
}

const saveTodo = () => {
  if (editingTodo.value) {
    const index = todos.value.findIndex(t => t.id === editingTodo.value.id)
    todos.value[index] = {
      ...editingTodo.value,
      ...todoForm.value,
      updatedAt: new Date().toISOString()
    }
  } else {
    todos.value.push({
      id: Date.now(),
      ...todoForm.value,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    })
  }

  showAddModal.value = false
  editingTodo.value = null
  todoForm.value = {
    title: '',
    description: '',
    status: 'todo',
    rating: 0
  }
}

const editTodo = (todo) => {
  editingTodo.value = todo
  todoForm.value = { ...todo }
  showAddModal.value = true
}

const deleteTodo = (id) => {
  if (confirm('确定要删除这个待办事项吗？')) {
    todos.value = todos.value.filter(todo => todo.id !== id)
  }
}
</script>

<style>
.prose {
  max-width: none;
}

.prose p {
  margin: 0;
}

.prose pre {
  background-color: #f3f4f6;
  padding: 1rem;
  border-radius: 0.375rem;
  margin: 0.5rem 0;
}

.prose code {
  background-color: #f3f4f6;
  padding: 0.2rem 0.4rem;
  border-radius: 0.25rem;
  font-size: 0.875em;
}

.prose blockquote {
  border-left: 4px solid #e5e7eb;
  padding-left: 1rem;
  margin: 0.5rem 0;
  color: #6b7280;
}

.prose ul,
.prose ol {
  margin: 0.5rem 0;
  padding-left: 1.5rem;
}

.prose li {
  margin: 0.25rem 0;
}
</style>